package com.example.xymarket.cim.http;

import android.os.Handler;

import java.util.HashMap;
import java.util.Map;

import com.example.xymarket.BuildConfig;
import com.example.xymarket.common.Info;
import com.farsunset.cim.sdk.android.model.Message;
import com.google.gson.Gson;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SendMessageManager {
    private Handler handler;
    private MessageService messageService = new Retrofit
            .Builder()
            .baseUrl(BuildConfig.CIM_API_URL + "/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MessageService.class);
    public SendMessageManager(Handler handler)
    {
        this.handler=handler;
    }

    public void send(final Message message) {
        try {
        Map<String, String> map = new HashMap<>();
        map.put("sender", message.getSender());
        map.put("receiver", message.getReceiver());
        map.put("action", message.getAction());
        map.put("content", message.getContent());
        Gson gson = new Gson();
        String res = gson.toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), res);

            messageService.send(requestBody, Info.getMyUserInfo().getToken()).enqueue(new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    android.os.Message message1=new android.os.Message();
                    message1.what=1;
                    message1.obj=message;
                    handler.sendMessage(message1);
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                    System.out.println("失败");
                }
            });
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }

}

